package saucaca.Adapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import saucaca.Object.SongObject;
import saucaca.Util.TagName;
import saucaca.fragment.LocalAllMusic;
import saucaca.fragment.LocalSonglistExpanded;
import saucaca.fragment.SelectPlaylistDialogOffline;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.RingtoneManager;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.MainActivity;
import com.lemon.kenhnhacvn.R;

@SuppressLint("NewApi")
public class SongAdapter extends BaseAdapter {
	Context context;
	private String tag;
	private LayoutInflater inflater;
	private ArrayList<Map<String, Object>> list;
	private ArrayList<SongObject> listSongs = new ArrayList<SongObject>();
	PopupMenu menuPop = null;
	SongObject songObject = null;
	int index = 0;

	public SongAdapter(Context context) {
		tag = "";
		list = new ArrayList<Map<String, Object>>();
		this.context = context;
		this.inflater = LayoutInflater.from(context);
	}

	void getListSong(ArrayList<Map<String, Object>> _list) {
		for (int i = 0; i < _list.size(); i++) {
			listSongs.add((SongObject) list.get(i).get(LocalAllMusic.Key_Music));
		}
	}

	public SongAdapter(Context context, ArrayList<Map<String, Object>> _list, String _tag) {
		tag = _tag;
		list = _list;
		this.context = context;
		this.inflater = LayoutInflater.from(context);
		getListSong(_list);
	}

	// public void setPotitionIndicator(int position) {
	// songPlaying = position;
	// notifyDataSetChanged();
	// }

	public String getTag() {
		return tag;
	}

	public void setList(ArrayList<Map<String, Object>> _list, String _tag) {
		list = _list;
		getListSong(_list);
		this.tag = _tag;
		notifyDataSetChanged();
	}

	public ArrayList<Map<String, Object>> getList() {
		return list;
	}

	class ViewHolder {
		LinearLayout layout;
		TextView textViewNumber;
		TextView textViewTitle;
		TextView textViewArtist;
		ImageView imgeView, img_album;
		ImageButton imgMenu;
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.item_song_local, null);
			holder.layout = (LinearLayout) convertView.findViewById(R.id.localmusic_linearSong);
			holder.img_album = (ImageView) convertView.findViewById(R.id.songlocalAvatar);
			holder.textViewNumber = (TextView) convertView.findViewById(R.id.song_number);
			holder.textViewTitle = (TextView) convertView.findViewById(R.id.song_title);
			holder.textViewArtist = (TextView) convertView.findViewById(R.id.song_artist);
			holder.imgMenu = (ImageButton) convertView.findViewById(R.id.popup_menu);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		final String title = list.get(position).get(LocalAllMusic.Key_Title).toString();
		final String artist = list.get(position).get(LocalAllMusic.Key_Artist).toString();

		menuPop = new PopupMenu(context, holder.imgMenu);
		holder.imgMenu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (tag.equals(LocalAllMusic.SONGS_MUSIC)) {
					try {
						songObject = (SongObject) list.get(position).get(LocalAllMusic.Key_Music);
						index = position;
					} catch (Exception e) {
					}
				}
				menuPop.show();
			}
		});
		if (tag.equals(LocalAllMusic.SONGS_MUSIC)) {
			menuPop.getMenuInflater().inflate(R.menu.popup_menu_song, menuPop.getMenu());
			menuPop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
				public boolean onMenuItemClick(MenuItem item) {
					switch (item.getItemId()) {
					case R.id.addqueu:
						try {
							((MainActivity) context).mPlaylistMgr.add(songObject);
						} catch (Exception e) {
							ArrayList<SongObject> lists = new ArrayList<SongObject>();
							lists.add(songObject);
							((MainActivity) context).SendPlaylistAndplay(lists, 0);
						}

						break;
					case R.id.addplaylist:
						DialogFragment df = null;
						df = SelectPlaylistDialogOffline.newInstance(songObject);
						df.show(((MainActivity) context).getSupportFragmentManager(), null);
						break;
					case R.id.ringtone:
						if (!songObject.getFormNet()) {
							new AlertDialog.Builder(context).setTitle("Cài nhạc chuông!")
									.setMessage("Bạn muốn cài bài hát:' " + songObject.getTXNAME() + "'" + " làm nhạc chuông?")
									.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog, int which) {

											ContentValues values = new ContentValues();
											values.put(MediaStore.MediaColumns.DATA, songObject.getPATCH_FULL());
											values.put(MediaStore.MediaColumns.TITLE, songObject.getTXNAME());
											values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
											values.put(MediaStore.Audio.Media.ARTIST, songObject.getNAME_SINGERS());
											values.put(MediaStore.Audio.Media.DURATION, songObject.getduration());
											values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
											values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
											values.put(MediaStore.Audio.Media.IS_ALARM, false);
											values.put(MediaStore.Audio.Media.IS_MUSIC, false);
											// Insert it into the
											// database
											Uri uri = MediaStore.Audio.Media.getContentUriForPath(songObject.getPATCH_FULL());
											Uri newUri = context.getContentResolver().insert(uri, values);
											RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
										}
									}).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog, int which) {
										}
									}).setIcon(android.R.drawable.ic_dialog_alert).show();

						} else
							TagName.showToastShort(context, "Tải bài hát về thiết bị trước khi cài nhạc chuông!");
						break;
					case R.id.delete:
						deleteDialog(songObject);
						break;
					default:
						break;
					}
					return true;
				}
			});
		} else if (tag.equals(LocalAllMusic.PLAYLIST_MUSIC)) {
			menuPop.getMenuInflater().inflate(R.menu.popup_playlist_list, menuPop.getMenu());
			menuPop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
				public boolean onMenuItemClick(MenuItem item) {
					switch (item.getItemId()) {
					case R.id.play:
						@SuppressWarnings("unchecked")
						ArrayList<SongObject> listShow = (ArrayList<SongObject>) list.get(position).get(LocalAllMusic.Key_List);
						if (listShow != null && listShow.size() > 0) {
							ArrayList<SongObject> listSongs = new ArrayList<SongObject>();
							for (int i = 0; i < listShow.size(); i++) {
								listSongs.add((SongObject) listShow.get(i));
							}
							((MainActivity) context).SendPlaylistAndplay(listSongs, 0);
							((MainActivity) context).showPanelControl(true);
						}
						break;
					case R.id.rename:
						TagName.showToastShort(context, "Rename");
						break;
					case R.id.delete:
						new AlertDialog.Builder(context).setTitle("Xóa playlist!").setMessage("Bạn muốn xóa :' " + title + "'" + " ?")
								.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int which) {
										try {
											LocalAllMusic.db.delMyPlayList(title);
											list.remove(position);
											notifyDataSetChanged();
										} catch (Exception e) {
										}
									}
								}).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int which) {
									}
								}).setIcon(android.R.drawable.ic_dialog_alert).show();

						break;
					default:
						break;
					}
					return true;
				}
			});
		} else
			holder.imgMenu.setVisibility(View.GONE);
		if (tag.equals(LocalAllMusic.ALBUM_MUSIC)) {
			try {
				Bitmap bm = BitmapFactory.decodeFile(list.get(position).get(LocalAllMusic.Key_Image).toString());
				if (bm != null) {
					@SuppressWarnings("deprecation")
					BitmapDrawable bmpDraw = new BitmapDrawable(bm);
					holder.img_album.setImageDrawable(bmpDraw);
				} else
					holder.img_album.setImageResource(R.drawable.default_list_album);
				holder.textViewNumber.setVisibility(View.GONE);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		holder.textViewNumber.setText(Integer.toString(position + 1));

		holder.textViewTitle.setText(title);
		holder.textViewArtist.setText(artist);

		if (tag.equals(LocalAllMusic.VIDEO_MUSIC)) {
			SongObject song = (SongObject) list.get(position).get(LocalAllMusic.Key_Music);
			long ids = Long.parseLong(song.getSONG_ID());
			ContentResolver crThumb = context.getContentResolver();
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 1;
			Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, ids, MediaStore.Video.Thumbnails.MICRO_KIND, options);
			holder.img_album.setImageBitmap(curThumb);
			curThumb = null;
			BaseEngine.setVideoclick(context, holder.layout, song);
			holder.textViewArtist.setVisibility(View.GONE);
			holder.textViewNumber.setVisibility(View.GONE);
		} else
			holder.layout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (tag.equals(LocalAllMusic.SONGS_MUSIC)) {
						((MainActivity) context).SendPlaylistAndplay(listSongs, position);
						((MainActivity) context).showPanelControl(true);
					} else {
						((MainActivity) context).switchContent(LocalSonglistExpanded.class.getName(), tag, position);
					}
				}
			});

		return convertView;
	}

	public void deleteDialog(final SongObject songObject) {
		AlertDialog builder = new AlertDialog.Builder(context).create();
		builder.setMessage("Bạn muốn xóa " + songObject.getTXNAME() + "?");
		builder.setCancelable(false);
		builder.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (((MainActivity) context).mPlaylistMgr.getCurrentSong() != songObject) {
					Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Integer.parseInt(songObject.getSONG_ID()));
					int i = context.getContentResolver().delete(uri, null, null);
					if (i == 1) {
						list.remove(index);
						((MainActivity) context).mPlaylistMgr.remove(songObject);
						// ((MainActivity)context).
						notifyDataSetChanged();
						Log.e("log_tag", "deleted: " + i);
					}
				} else {
					Toast.makeText(context, "Bài hát đang được phát!", Toast.LENGTH_SHORT).show();
				}
			}
		});
		builder.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.show();
	}

}
